using System.Collections.Generic;
using UnityEngine;

public class GridManager
{
    protected readonly Dictionary<Vector2Int, IGridTransform> objects = new Dictionary<Vector2Int, IGridTransform>();

    public int Count_Occupy => objects.Count;

    public void Register(IGridTransform obj)
    {
        if (objects.ContainsKey(obj.GridTransform.Position))
            Unregister(obj.GridTransform.Position);
        objects.Add(obj.GridTransform.Position, obj);
    }
    public void Unregister(Vector2Int position)
    {
        objects.Remove(position);
    }

    public void UnregisterAll()
        => objects.Clear();

    public T GetObjectAt<T>(Vector2Int position) where T : IGridTransform
    {
        if (objects.ContainsKey(position))
            return (T)objects[position];
        return default;
    }

    public List<T> GetObjectsAt<T>(List<Vector2Int> positions) where T : IGridTransform
    {
        List<T> ret = new List<T>();
        T objects;
        foreach (Vector2Int position in positions)
        {
            objects = GetObjectAt<T>(position);
            if (objects != null)
                ret.Add(objects);
        }
        return ret;
    }
    public void GetObjectsAt<T>(List<Vector2Int> positions, List<T> ret) where T : IGridTransform
    {
        ret.Clear();
        T objects;
        foreach (Vector2Int position in positions)
        {
            objects = GetObjectAt<T>(position);
            if (objects != null)
                ret.Add(objects);
        }
    }

    public bool HasObject(Vector2Int position)
    {
        return objects.ContainsKey(position);
    }
}
